<?php
if (!defined('__COLA_DIR__')) exit;

/**
 * 上传组件
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Widget_Upload extends Widget_Attachs_Edit
{
	
    /** 上传文件目录 (物理路径，可以用 NFS 存入到单独的文件服务器) */
    public static $uploadPath = '/usr/uploads';
	
    /**
     * 创建上传路径
     *
     * @access private
     * @param string $path 路径
     * @return boolean
     */
    private static function makeUploadDir($path)
    {
        $path = preg_replace("/\\\+/", '/', $path);
        $current = rtrim($path, '/');
        $last = $current;

        while (!is_dir($current) && false !== strpos($path, '/')) {
            $last = $current;
            $current = dirname($current);
        }

        if ($last == $current) {
            return true;
        }

        if (!@mkdir($last)) {
            return false;
        }

        $stat = @stat($last);
        $perms = $stat['mode'] & 0007777;
        @chmod($last, $perms);

        return self::makeUploadDir($path);
    }

    /**
     * 获取安全的文件名 
     * 
     * @param string $name 
     * @static
     * @access private
     * @return string
     */
    private static function getSafeName(&$name)
    {
        $name = str_replace(array('"', '<', '>'), '', $name);
        $name = str_replace('\\', '/', $name);
        $name = false === strpos($name, '/') ? ('a' . $name) : str_replace('/', '/a', $name);
        $info = pathinfo($name);
        $name = substr($info['basename'], 1);
    
        return isset($info['extension']) ? strtolower($info['extension']) : '';
    }

    /**
     * 检查文件名
     *
     * @access private
     * @param string $ext 扩展名
     * @return boolean
     */
    public static function checkFileType($ext)
    {
        $options = Cola::widget('Widget_Options');
        return in_array($ext, $options->allowedAttachmentTypes);
    }

	
    /**
     * 上传文件处理函数
     *
     * @access public
     * @param array $file 上传的文件
     * @return mixed
     */
    public static function uploadHandle($file)
    {
        if (empty($file['name'])) {
            return false;
        }
        
		/** 插件接口 实现自己的文件哈希或者特殊的文件系统 */
		//HOOK {$plugged} $result | PLUG_UploadHandle($file);
		
        if ($plugged) {
            return $result;
        }

        $ext = self::getSafeName($file['name']);

        if (!self::checkFileType($ext) || Common::isAppEngine()) {
            return false;
        }

		//文件路径
        $date = new Date();
        $path = Common::url(self::$uploadPath, __COLA_DIR__) . '/' . $date->year . '/' . $date->month;

        //创建上传目录
        if (!is_dir($path)) {
            if (!self::makeUploadDir($path)) {
                return false;
            }
        }

        //获取文件名
        $fileName = sprintf('%u', crc32(uniqid())) . '.' . $ext;
        $path = $path . '/' . $fileName;

        if (isset($file['tmp_name'])) {

            //移动上传文件
            if (!@move_uploaded_file($file['tmp_name'], $path)) {
                return false;
            }
        } else if (isset($file['bytes'])) {

            //直接写入文件
            if (!file_put_contents($path, $file['bytes'])) {
                return false;
            }
        } else {
            return false;
        }

        if (!isset($file['size'])) {
            $file['size'] = filesize($path);
        }

        //返回相对存储路径
        return array(
            'name' => $file['name'],
            'path' => '/' . $date->year . '/' . $date->month . '/' . $fileName,
            'size' => $file['size'],
            'type' => $ext,
            'mime' => Common::mimeContentType($path)
        );
    }

	
    /**
     * 执行升级程序
     *
     * @access public
     * @return void
     */
    public function upload($type, $id)
    {
        if (!empty($_FILES)) {
            $file = array_pop($_FILES);
            if (0 == $file['error'] && is_uploaded_file($file['tmp_name'])) {
                // xhr的send无法支持utf8
                if ($this->request->isAjax()) {
                    $file['name'] = urldecode($file['name']);
                }
				
                $result = self::uploadHandle($file);

                if (false === $result) {
					return false;
				}	

                $values = array(
                    'id'            =>  $id,
                    'type'          =>  $type,
                    'fileName'      =>  $result['name'],
                    'fileType'      =>  $result['type'],
                    'fileSize'      =>  $result['size'],
                    'filePath'      =>  $result['path'],
                    'created'       =>  $this->options->time,
                    'isImage'       =>  in_array($result['type'], array('jpg', 'jpeg', 'gif', 'png', 'tiff', 'bmp')),
                    'uid'           =>  $this->user->uid,
                );
				
                /** 插件接口 */
				//HOOK $values | PLUG_Upload($values, $this);

                $insertId = $this->insert($values);
                $attach = $this->select()
				    ->where('table.attachs.aid = ?', $insertId)
                    ->fetchRow(array($this, 'push'));

                /** 插件接口 */
				//HOOK PLUG_Upload_Success($this);

                return $attach;
            }
        }

        return false;
    }

    /**
     * 绑定动作
     *
     * @access public
     * @return void
     */
    public function action()
    {
        $this->security->protect();  

		$type = $this->request->filter('strip_tags')->type;
		$id   = $this->request->filter('int')->id;
		$attach = $this->upload($type, $id);

        if (!empty($attach)) {
			$this->result->setAjax(true)->set(0, _t('上传成功'), $attach);
        } else {
			$this->result->setAjax(true)->set(1, _t('上传失败'));
		}
	}
}
